package MichaelMilewski;

use warnings;
use strict;

use LWP::UserAgent;
use JSON;
# TODO or Image::Caa and Image::Magick

sub isBeautifulNumber {
    return unless @_;
    my $number = shift;
    return googleImageSearch($number);# if $number == 1234567890 or $number == 1234567890987654321;
    if($@) {
        # do nothing
    }
    return $number;
}

sub googleImageSearch {
    my $number = shift;
    my $response = fetchGoogleImageSearchResponse($number);
#    warn $response;
    my $json = new JSON;
    my $perl_scalar = $json->decode($response);
    # get first best result
    return $perl_scalar->{results}->[0]->{url};
}

sub fetchGoogleImageSearchResponse {
    my $number = shift;   
    my $ua = LWP::UserAgent->new;
    $ua->timeout(10);
    my $response = $ua->get(sprintf(
        'http://www.google.com/uds/GimageSearch?callback=google.search.ImageSearch.RawCompletion&context=1&lstkp=0&rsz=large&hl=en&gss=.com&sig=9f362c5f2d2bc9f3c3f4585dc7dae979&q=%s&key=notsupplied&v=1.0',
        $number
    ));
 
    if ($response->is_success) {
        my $content = $response->content;
        # TODO neater way around this?
        $content =~ s/^google.search.ImageSearch.RawCompletion\('1',//;
        $content =~ s/, 200, null, 200\)//;
        #warn $content;
        # TODO if no result will get a 
        return $content;
    }
    # TODO handle this somehow
    else {
        die $response->status_line;
    }
}

1;